package com.yxm.springbootsecurity.Serializable;


import com.yxm.springbootsecurity.entity.Evil;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

@Component
public class EvilSerialize {
    public static void main(String[] args) throws Exception {
        Evil evil = new Evil();
//        evilObj.setName("calc");
        // mac
        evil.setName("Calculator");

        // 序列化为字节数组
        byte[] bytes = serializeToBytes(evil);
        System.out.println(bytes);
        // 反序列化
        Evil o = (Evil)deserializeFromBytes(bytes);
        System.out.println(o);
    }

    public static byte[] serializeToBytes(final Object obj) throws Exception {
        final ByteArrayOutputStream out = new ByteArrayOutputStream();
        final ObjectOutputStream objOut = new ObjectOutputStream(out);
        objOut.writeObject(obj);
        objOut.flush();
        objOut.close();
        return out.toByteArray();
    }

    public static Object deserializeFromBytes(final byte[] serialized) throws Exception {
        final ByteArrayInputStream in = new ByteArrayInputStream(serialized);
        final ObjectInputStream objIn = new ObjectInputStream(in);
        return objIn.readObject();
    }
}
